define(["jquery", "easy-admin"], function ($, ea) {

    var init = {
        table_elem: '#currentTable',
        table_render_id: 'currentTableRenderId',
        index_url: 'index',
        add_url: 'add',
        edit_url: 'edit',
        delete_url: 'del',
        export_url: 'export',
        modify_url: 'modify',
        detail: 'index/detail',
        backup: 'index/backup',
        optimize: 'index/optimize',
        repair: 'index/repair',
    };

    var backup_init = {
        table_elem: '#currentTable2',
        table_render_id: 'currentTableRenderId2',
        add_url: 'add',
        edit_url: 'edit',
        delete_url: 'index/del',
        export_url: 'index/export',
        modify_url: 'modify',
        index_url: 'index/backupList',
        import_url: 'index/import',
        download_url: 'download',
        process_url: 'index/process',
    };

    var table = layui.table;

    var Controller = {

        index: function () {
            ea.table.render({
                init: init,
                cols: [[
                    {type: 'checkbox'},
                    {field: 'name', title: '表名称', align:'left',search: false},
                    {field: 'comment', title: '备注',align:'left', search: false},
                    {field: 'engine', title: '引擎', search: false, sort: true},
                    {field: 'collation', title: '编码格式',align:'left', search: false, sort: true},
                    {field: 'data_length', title: '表大小', search: false,templet:show_size, sort: true},
                    {field: 'data_free', title: '碎片大小', search: false,templet:show_free, sort: true},
                    {field: 'update_time', title: '更新时间', search: false, sort: true},
                    {field: 'rows', title: '行数', search: false, sort: true},
                    {
                        width: 250, title: '操作', templet: ea.table.tool
                        , operat: [
                            [{
                                text: '详情',
                                url: detail_url,
                                method: 'open',
                                auth: 'detail',
                                class: 'layui-btn layui-btn-xs layui-btn-success',
                                extend: '',
                            }]]
                    },
                ]],
                limit: 2000,
            });
            ea.table.render({
                init: backup_init,
                cols: [[
                    // {type: 'checkbox'},
                    {field: 'filename', title: '备份名称', width:'20%', search: false},
                    {field: 'part', title: '文件数量', width:'10%', search: false},
                    {field: 'size', title: '大小',  width:'10%',search: false},
                    {field: 'compress', title: '压缩格式', width:'10%', search: false},
                    {field: 'backtime', title: '时间', width:'19%', search: false},
                    {
                        width:'30%', title: '操作', templet: ea.table.tool
                        , operat: [
                            [
                                {
                                    text: '导入（备份覆盖）',
                                    url: import_url,
                                    method: 'request',
                                    auth: 'import',
                                    class: 'layui-btn layui-btn-xs layui-btn-success import_data',
                                    extend: 'data-flag="true"',
                                    callback: process.open,
                                },
                                {
                                    text: '下载备份',
                                    url: download,
                                    method: 'url',
                                    auth: 'download',
                                    class: 'layui-btn layui-btn-xs layui-btn-normal',
                                    extend: '',
                                },
                                {
                                    text: '删除',
                                    url: delete_url,
                                    method: 'request',
                                    auth: 'del',
                                    class: 'layui-btn layui-btn-xs layui-btn-danger',
                                    extend: '',
                                },
                            ]]
                    },
                ]],
            });


            backup.listen();//监听备份,优化，修复
            ea.listen();
        },
        process: function () {
            process.location();
            process.listen();
            ea.listen();
        }
    };

    var download = function (data) {
        return backup_init.download_url + '?time=' + data.time
    }

    var import_url = function (data) {
        return backup_init.import_url + '?time=' + data.time
    }

    var delete_url = function (data) {
        return backup_init.delete_url + '?time=' + data.time
    }

    var detail_url = function (data) {
        return init.detail + '?table_name=' + data.name
    }
    var show_free = function (data) {
        if(!data.data_free){
            return "<span style='color: grey'>"+data.data_free_format+"</span>";
        }else{
            return "<span style='color: red'>"+data.data_free_format+"</span>";
        }
    }

    var show_size = function (data) {
        return data.data_length_format;
    }

    var backup = {
        param: {},
        build: function (callBack) {
            var names = backup.getNames();
            if (!names) {
                ea.msg.error('请选择要备份的表');
                return;
            }
            ea.request.post({
                url: '/' + module_name + '/' + init.backup,
                data: {
                    tables: names
                }
            }, function (res) {
                callBack(res.data.data, res.msg);
            }, function (res) {
                //失败
                callBack(null, res.msg);
            }, function (that) {
                //异常
                callBack(null, '备份失败');
            });
        },
        optimize: function (callBack) {
            var names = backup.getNames();
            if (!names) {
                ea.msg.error('请选择要优化的表');
                return;
            }
            ea.request.post({
                url: '/' + module_name + '/' + init.optimize,
                data: {
                    tables: names
                }
            }, function (res) {
                callBack(res.data.data, res.msg);
            }, function (res) {
                //失败
                callBack(null, res.msg);
            }, function (that) {
                //异常
                callBack(null, '优化失败');
            });
        },
        repair: function (callBack) {
            var names = backup.getNames();
            if (!names) {
                ea.msg.error('请选择要修复的表');
                return;
            }
            ea.request.post({
                url: '/' + module_name + '/' + init.repair,
                data: {
                    tables: names
                }
            }, function (res) {
                callBack(res.data.data, res.msg);
            }, function (res) {
                //失败
                callBack(null, res.msg);
            }, function (that) {
                //异常
                callBack(null, '修复失败');
            });
        },
        getNames: function () {
            var checkStatus = table.checkStatus(init.table_render_id);
            data = checkStatus.data;
            if (data.length <= 0) {
                return false;
            }
            var ids = [];
            $.each(data, function (i, v) {
                ids.push(v.name);
            });
            return ids.join(",");
        },
        listen: function () {
            $('#backup').click(function () {

                backup.build(function (data, error_msg) {
                    if (data) {
                        console.log(data);
                        ea.msg.success(error_msg);
                        //备份成功刷新表格
                        ea.table_reload();
                    } else {
                        ea.msg.error(error_msg);
                    }
                });
            });

            $('#optimize').click(function () {

                backup.optimize(function (data, error_msg) {
                    if (data) {
                        console.log(data);
                        ea.msg.success(error_msg);
                        //备份成功刷新表格
                        ea.table_reload();
                    } else {
                        ea.msg.error(error_msg);
                    }
                });
            });

            $('#repair').click(function () {

                backup.repair(function (data, error_msg) {
                    if (data) {
                        console.log(data);
                        ea.msg.success(error_msg);
                        //备份成功刷新表格
                        ea.table_reload();
                    } else {
                        ea.msg.error(error_msg);
                    }
                });
            });
        }

    }

    var process = {
        param: {
            logs: [],
            install_index: 0,
            timer: 0,
        },
        open: function () {
            process.param.install_index = layer.open({
                type: 2,
                title: '正在执行数据覆盖，时间较长，过程中请勿关闭本页面...',
                closeBtn: 0, //不显示关闭按钮
                shade: [0],
                area: ['640px', '415px'],
                offset: 'rb', //右下角弹出
                anim: 2,
                content: ['/' + module_name + '/' + backup_init.process_url], //iframe的url，no代表不显示滚动条
            });

        },
        listen: function () {
            process.param.timer = setInterval(process.loop, 500);  //指定1秒刷新一次
        },
        loop: function () {
            process.build(function (datas, error_msg) {
                console.log(datas);
                //备份中
                if (datas) {
                    if (datas.length > process.param.logs.length) {
                        process.param.logs = datas;
                        var html = '';
                        for (var i = 0; i < datas.length; i++) {
                            html += ('<div>' + datas[i] + '</div>');
                        }
                        $('#log').html(html);
                        process.location();
                    }
                } else {
                    clearInterval(process.param.timer);
                    var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                    parent.layer.close(index); //再执行关闭
                    //导入完成
                    ea.table_reload();
                }
            });
        },
        location: function () {
            var c = window.document.body.scrollHeight;
            window.scroll(0, c);
        },
        build: function (callBack) {
            ea.request.post({
                url: '/' + module_name + '/' + backup_init.process_url,
            }, function (res) {
                callBack(res.data.data, res.msg);
            }, function (res) {
                //失败
                callBack(null, res.msg);
            }, function (that) {
                //异常
                callBack(null, '备份失败');
            });
        },
    }

    return Controller;
});